<template>
  <div class="app-container">
    <!-- 第一栏：目标网站选择 -->
    <div class="filter-container" style="margin-bottom: 15px; padding: 15px; background: #f5f7fa; border-radius: 4px;">
      <div style="display: flex; align-items: center;">
        <span style="font-weight: 600; margin-right: 10px; color: #606266;">目标网站：</span>
        <el-select
          v-model="currentWebsite"
          value-key="id"
          placeholder="选择目标静态网站"
          style="width: 400px;"
          filterable
          @change="handleWebsiteChange"
        >
          <el-option
            v-for="site in websites"
            :key="site.id"
            :label="site.name + ' (' + site.domain + ')'"
            :value="site"
          />
        </el-select>
        <el-button
          style="margin-left: 10px;"
          icon="el-icon-refresh"
          @click="loadWebsites"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 第二栏：文章筛选条件 -->
    <div class="filter-container" style="margin-bottom: 15px;">
      <span style="font-weight: 600; margin-right: 10px; color: #606266;">文章筛选：</span>
      <el-select
        v-model="postsQuery.category_id"
        placeholder="分类"
        clearable
        filterable
        style="width: 150px;"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="cat in categories"
          :key="cat.id"
          :label="cat.name"
          :value="cat.id"
        />
      </el-select>

      <el-select
        v-model="postsQuery.language_id"
        placeholder="语言"
        clearable
        style="width: 120px; margin-left: 10px;"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="lang in languages"
          :key="lang.id"
          :label="lang.name"
          :value="lang.id"
        />
      </el-select>

      <el-select
        v-model="postsQuery.publish_status"
        placeholder="配置状态"
        clearable
        style="width: 160px; margin-left: 10px;"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option label="全部" value="all" />
        <el-option label="未配置" value="unpublished" />
        <el-option label="已配置" value="published" />
        <el-option label="其他网站已配置" value="published_other" />
      </el-select>

      <el-select
        v-model="postsQuery.writer_finished"
        placeholder="写作状态"
        clearable
        style="width: 140px; margin-left: 10px;"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option label="全部" value="" />
        <el-option label="写作完成" value="1" />
        <el-option label="未完成" value="0" />
      </el-select>

      <el-input
        v-model="postsQuery.kw"
        placeholder="搜索标题、内容、标签..."
        clearable
        style="width: 200px; margin-left: 10px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />

      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        style="margin-left: 10px;"
        @click="handleFilter"
      >
        搜索
      </el-button>
    </div>

    <!-- 第三栏：批量操作 -->
    <div v-if="selectedPosts.length > 0" class="filter-container" style="margin-bottom: 15px; padding: 10px; background: #ecf5ff; border: 1px solid #b3d8ff; border-radius: 4px;">
      <span style="color: #409eff; font-weight: 600;">已选择 {{ selectedPosts.length }} 篇文章</span>
      <el-button
        type="success"
        icon="el-icon-setting"
        size="small"
        style="margin-left: 15px;"
        @click="batchPublish"
      >
        批量配置页面
      </el-button>
      <el-button
        type="info"
        size="small"
        plain
        @click="clearSelection"
      >
        清空选择
      </el-button>
    </div>

    <!-- 文章列表 -->
    <div v-loading="postsLoading" class="posts-list" style="margin-top: 20px;">
      <div
        v-for="post in postsList"
        :key="post.id"
        class="post-item"
        :class="{
          'is-selected': isPostSelected(post.id),
          'published-to-current': post.is_published_to_current
        }"
      >
        <!-- 左侧勾选框 -->
        <div class="post-checkbox">
          <el-checkbox
            :value="isPostSelected(post.id)"
            @change="togglePostSelection(post)"
          />
        </div>

        <!-- 中间内容区 -->
        <div class="post-content">
          <div class="post-title">
            {{ post.title }}
          </div>
          <div class="post-meta">
            <el-tag v-if="post.category__name" size="mini" type="info">{{ post.category__name }}</el-tag>
            <el-tag v-if="post.language__name" size="mini">{{ post.language__name }}</el-tag>
            <span class="meta-item">字数: {{ post.word_count || 0 }}</span>
            <span v-if="post.writer_finished_at" class="meta-item">{{ post.writer_finished_at }}</span>
          </div>
          <div v-if="post.excerpt" class="post-excerpt">
            {{ post.excerpt }}
          </div>
        </div>

        <!-- 发布状态和操作 -->
        <div class="post-status-actions">
          <!-- 发布状态标签 -->
          <div class="status-tags">
            <el-tag
              v-if="post.is_published_to_current"
              type="success"
              size="small"
              effect="dark"
            >
              <i class="el-icon-check" /> 已配置页面
            </el-tag>
            <el-tag
              v-else-if="post.published_to_other_websites_count > 0"
              type="warning"
              size="small"
            >
              <i class="el-icon-warning" /> 其他网站已配置({{ post.published_to_other_websites_count }}个)
            </el-tag>
            <el-tag
              v-else
              type="info"
              size="small"
            >
              <i class="el-icon-remove" /> 未配置
            </el-tag>

            <!-- 如果已发布，显示页面状态 -->
            <el-tag
              v-if="post.is_published_to_current && post.current_website_page_status"
              :type="post.current_website_page_status === 'published' ? 'success' : 'warning'"
              size="mini"
              style="margin-left: 5px;"
            >
              {{ getStatusText(post.current_website_page_status) }}
            </el-tag>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button
              v-if="post.is_published_to_current"
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="openPublishDrawer(post)"
            >
              更新配置
            </el-button>
            <el-button
              v-else
              type="success"
              size="small"
              icon="el-icon-setting"
              @click="openPublishDrawer(post)"
            >
              配置页面
            </el-button>
            <el-button
              v-if="post.is_published_to_current"
              type="warning"
              size="small"
              icon="el-icon-upload"
              @click="handleDeployBlog(post)"
            >
              部署到网站
            </el-button>
            <el-button
              type="info"
              size="small"
              plain
              icon="el-icon-view"
              @click="previewPost(post)"
            >
              预览
            </el-button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="!postsLoading && postsList.length === 0" description="暂无符合条件的文章" />
    </div>

    <!-- 分页 -->
    <el-pagination
      v-if="postsTotal > 0"
      background
      class="mt-pagination"
      style="margin-top: 20px; text-align: right;"
      :current-page="postsQuery.page"
      :page-sizes="[10, 20, 50]"
      :page-size="postsQuery.pagesize"
      layout="total, sizes, prev, pager, next"
      :total="postsTotal"
      @size-change="handlePostsSizeChange"
      @current-change="handlePostsPageChange"
    />

    <!-- 发布配置抽屉 -->
    <el-drawer
      :title="publishDrawerTitle"
      :visible.sync="publishDrawerVisible"
      size="80%"
      :close-on-click-modal="false"
    >
      <div class="drawer-split-layout">
        <!-- 左侧：表单 -->
        <div class="left-panel">
          <el-form
            ref="publishForm"
            :model="publishForm"
            :rules="publishRules"
            label-width="120px"
          >
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="publishForm.title" placeholder="请输入文章标题" />
            </el-form-item>

            <el-form-item label="URL Slug" prop="slug">
              <el-input v-model="publishForm.slug" placeholder="例如: my-blog-post">
                <template slot="prepend">{{ currentWebsite ? currentWebsite.domain + '/' : '' }}</template>
              </el-input>
            </el-form-item>

            <el-form-item label="选择模板" prop="template_id">
              <el-select v-model="publishForm.template_id" placeholder="请选择博客模板" style="width: 100%;" @change="handleTemplateChange">
                <el-option
                  v-for="tpl in templates"
                  :key="tpl.id"
                  :label="tpl.name"
                  :value="tpl.id"
                >
                  <span>{{ tpl.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px;">{{ tpl.description }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <!-- 显示模板占位符配置 -->
            <el-form-item v-if="selectedTemplate && selectedTemplate.placeholder_config" label="模板占位符">
              <el-alert
                type="info"
                :closable="false"
                style="margin-bottom: 10px;"
              >
                <div slot="title" style="font-size: 13px; line-height: 1.6;">
                  <strong>{{ selectedTemplate.name }}</strong> 需要以下占位符：
                </div>
                <pre style="margin: 10px 0 0 0; font-size: 12px; line-height: 1.6; max-height: 200px; overflow-y: auto;">{{ selectedTemplate.placeholder_config }}</pre>
              </el-alert>
            </el-form-item>

            <el-form-item label="特色图片">
              <div style="display: flex; align-items: flex-start; gap: 10px;">
                <div style="flex: 1;">
                  <el-input
                    v-model="publishForm.feature_image"
                    placeholder="图片URL或点击AI生成按钮"
                    readonly
                  >
                    <template slot="prepend">
                      <i class="el-icon-picture" />
                    </template>
                  </el-input>
                  <div v-if="publishForm.feature_image" style="margin-top: 10px;">
                    <img :src="publishForm.feature_image" alt="特色图片预览" style="max-width: 100%; max-height: 200px; border-radius: 4px; border: 1px solid #dcdfe6;">
                  </div>
                </div>
                <div style="display: flex; flex-direction: column; gap: 8px;">
                  <el-button
                    size="small"
                    icon="el-icon-magic-stick"
                    style="background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
                    @click="openFeatureImageDialog"
                  >
                    AI生成
                  </el-button>
                  <el-button
                    v-if="publishForm.feature_image"
                    size="small"
                    type="danger"
                    icon="el-icon-delete"
                    plain
                    @click="publishForm.feature_image = ''"
                  >
                    清除
                  </el-button>
                </div>
              </div>
              <div style="margin-top: 8px; font-size: 12px; color: #909399;">
                <i class="el-icon-info" />
                特色图片将作为 %%feature_image%% 占位符，用于博客文章顶部展示（默认21:9比例）
              </div>
            </el-form-item>

            <el-form-item label="模板变量配置">
              <el-input
                v-model="publishForm.template_variables"
                type="textarea"
                :rows="8"
                :placeholder="templateVariablesPlaceholder"
              />
              <div style="margin-top: 8px; font-size: 12px; color: #909399;">
                <i class="el-icon-info" />
                点击右侧 AI 助手，让 AI 根据上方模板占位符和文章内容自动生成配置
              </div>
            </el-form-item>

            <el-form-item label="页面类型">
              <el-radio-group v-model="publishForm.page_type">
                <el-radio label="blog">博客文章</el-radio>
                <el-radio label="page">普通页面</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="发布状态">
              <el-radio-group v-model="publishForm.status">
                <el-radio label="draft">草稿</el-radio>
                <el-radio label="published">已发布</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="SEO 标题">
              <el-input v-model="publishForm.seo_title" placeholder="50-60字符，包含主关键词" maxlength="60" show-word-limit />
              <div style="margin-top: 5px; font-size: 12px; color: #909399;">
                优化搜索引擎显示的标题，与文章标题可以不同
              </div>
            </el-form-item>

            <el-form-item label="SEO 关键词">
              <el-input v-model="publishForm.seo_keywords" type="textarea" :rows="2" placeholder="多个关键词用逗号分隔，例如：自定义旗帜, 旗帜设计, 旗帜制作" />
            </el-form-item>

            <el-form-item label="SEO 描述">
              <el-input v-model="publishForm.seo_description" type="textarea" :rows="3" placeholder="150-160字符，简洁描述页面内容" maxlength="160" show-word-limit />
            </el-form-item>

            <div class="drawer-footer">
              <el-button @click="publishDrawerVisible = false">取消</el-button>
              <el-button type="primary" :loading="publishLoading" @click="handlePublish">
                保存配置
              </el-button>
            </div>
          </el-form>
        </div>

        <!-- 右侧：AI 助手 -->
        <div class="right-panel-ai">
          <div class="ai-panel-header">
            <i class="el-icon-magic-stick" style="color: #1EB7E6;" />
            <span style="margin-left: 8px; font-weight: 600; font-size: 16px;">AI 发布助手</span>
          </div>
          <AIInnerChat
            ref="aiInnerChat"
            api-url="/static_web/api/ai/chat/"
            handler-name="blog_publisher"
            :context-data="publishAIContextComputed"
            :suggested-questions="aiSuggestedQuestions"
            placeholder="例如：根据当前模板和文章内容，生成模板变量配置..."
            @fill-form="handleAIFillForm"
          />
        </div>
      </div>
    </el-drawer>

    <!-- 特色图片生成对话框 -->
    <el-dialog
      title="AI生成特色图片"
      :visible.sync="featureImageDialogVisible"
      width="700px"
      append-to-body
      @close="handleFeatureImageDialogClose"
    >
      <el-form label-width="100px">
        <el-form-item label="图片描述">
          <el-input
            v-model="aiImagePrompt"
            type="textarea"
            :rows="4"
            placeholder="请输入图片描述，例如：一张展示产品特性的专业摄影图片"
          />
          <div style="margin-top: 8px; display: flex; align-items: center; justify-content: space-between;">
            <div style="font-size: 12px; color: #909399;">
              提示：描述越详细，生成的图片越符合预期
            </div>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh"
              :loading="generatingPrompt"
              style="color: #1EB7E6;"
              @click="regenerateImagePrompt"
            >
              {{ generatingPrompt ? '正在生成...' : '重新生成Prompt' }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="图片比例">
          <el-select v-model="aiImageAspectRatio" placeholder="请选择比例">
            <el-option label="21:9 超宽 (1536×672) 推荐" value="21:9" />
            <el-option label="16:9 横向 (1344×768)" value="16:9" />
            <el-option label="3:2 横向 (1248×832)" value="3:2" />
            <el-option label="4:3 横向 (1184×864)" value="4:3" />
            <el-option label="1:1 正方形 (1024×1024)" value="1:1" />
            <el-option label="2:3 纵向 (832×1248)" value="2:3" />
            <el-option label="3:4 纵向 (864×1184)" value="3:4" />
            <el-option label="9:16 纵向 (768×1344)" value="9:16" />
          </el-select>
        </el-form-item>

        <el-form-item label="压缩质量">
          <el-slider
            v-model="aiImageQuality"
            :min="1"
            :max="100"
            :marks="{ 1: '最小', 50: '中等', 100: '最高' }"
            show-input
            style="width: 400px;"
          />
          <div style="margin-top: 8px; font-size: 12px; color: #909399;">
            quality=85 推荐（平衡质量和文件大小）
          </div>
        </el-form-item>

        <!-- 实时日志显示 -->
        <el-form-item v-if="aiImageGenerationLog" label="生成过程">
          <div
            style="
              max-height: 200px;
              overflow-y: auto;
              padding: 10px;
              background: #f5f7fa;
              border-radius: 4px;
              font-size: 12px;
              white-space: pre-wrap;
              font-family: monospace;
            "
          >
            {{ aiImageGenerationLog }}
          </div>
        </el-form-item>

        <!-- 生成的图片预览 -->
        <el-form-item v-if="generatedImagePreview" label="生成结果">
          <div style="text-align: center;">
            <img
              :src="generatedImagePreview"
              alt="生成的特色图片"
              style="max-width: 100%; max-height: 300px; border-radius: 4px; border: 1px solid #dcdfe6;"
            >
            <div style="margin-top: 10px; font-size: 12px; color: #67C23A;">
              <i class="el-icon-success" /> 图片生成成功！点击"确认使用"应用到特色图片
            </div>
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="featureImageDialogVisible = false">取消</el-button>
        <el-button
          v-if="!generatedImagePreview"
          type="primary"
          icon="el-icon-magic-stick"
          style="background-color: #1EB7E6; border-color: #1EB7E6;"
          :loading="aiGeneratingImage"
          @click="handleAIGenerateFeatureImage"
        >
          {{ aiGeneratingImage ? 'AI 生成中...' : 'AI 生成图片' }}
        </el-button>
        <el-button
          v-if="generatedImagePreview"
          type="success"
          icon="el-icon-check"
          @click="confirmUseGeneratedImage"
        >
          确认使用
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Get as GetWebsites } from '@/api/static_web/website'
import { Get as GetTemplates } from '@/api/static_web_template'
import { GetPostsForPublish, PublishBlog, BatchPublishBlog, DeployBlogToStatic } from '@/api/static_web/batch-blog'
import { Get as GetCategories } from '@/api/cms/category'
import { Get as GetLanguages } from '@/api/cms/language'
import AIInnerChat from '@/components/AIInnerChat'
import request from '@/utils/request'

export default {
  name: 'StaticWebBatchBlog',
  components: {
    AIInnerChat
  },
  data() {
    return {
      // 网站列表
      websites: [],
      currentWebsite: null,

      // 模板列表
      templates: [],

      // 分类和语言
      categories: [],
      languages: [],

      // 文章列表
      postsLoading: false,
      postsList: [],
      postsTotal: 0,
      postsQuery: {
        page: 1,
        pagesize: 20,
        category_id: '',
        language_id: '',
        kw: '',
        publish_status: 'all', // 发布状态: all/unpublished/published/published_other
        writer_finished: '1' // 写完的: ''/0/1
      },

      // 已选择的文章
      selectedPosts: [],

      // 发布抽屉
      publishDrawerVisible: false,
      publishDrawerTitle: '发布文章',
      publishLoading: false,
      generatingFeatureImage: false, // AI生成特色图片中（已废弃）

      // 特色图片生成对话框
      featureImageDialogVisible: false,
      aiImagePrompt: '',
      aiImageAspectRatio: '21:9',
      aiImageQuality: 85,
      generatingPrompt: false,
      aiGeneratingImage: false,
      aiImageGenerationLog: '',
      generatedImagePreview: '',

      publishForm: {
        post_id: null,
        title: '',
        slug: '',
        template_id: null,
        template_variables: '', // 模板变量配置 JSON
        feature_image: '', // 特色图片URL
        page_type: 'blog',
        status: 'published',
        seo_title: '',
        seo_keywords: '',
        seo_description: ''
      },
      publishRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' }
        ],
        slug: [
          { required: true, message: '请输入URL Slug', trigger: 'blur' }
        ],
        template_id: [
          { required: true, message: '请选择模板', trigger: 'change' }
        ]
      },

      // 当前正在发布的文章
      currentPost: null,

      // AI 助手建议问题
      aiSuggestedQuestions: [
        {
          icon: 'el-icon-magic-stick',
          color: '#1EB7E6',
          title: '生成模板配置',
          question: '根据当前模板的占位符和文章内容，生成完整的模板变量配置、SEO标题、关键词、描述和URL Slug'
        },
        {
          icon: 'el-icon-document',
          color: '#409EFF',
          title: '优化SEO信息',
          question: '根据文章内容，生成优化的 SEO 标题、关键词和描述'
        },
        {
          icon: 'el-icon-edit',
          color: '#67C23A',
          title: '生成URL Slug',
          question: '根据文章标题，生成符合SEO规范的 URL Slug'
        }
      ]
    }
  },
  computed: {
    // 当前选中的模板
    selectedTemplate() {
      return this.templates.find(t => t.id === this.publishForm.template_id)
    },

    // 模板变量配置的占位符提示
    templateVariablesPlaceholder() {
      if (!this.selectedTemplate || !this.selectedTemplate.placeholder_config) {
        return '请先选择模板，AI 将根据模板和文章内容自动生成 JSON 配置'
      }

      try {
        const config = JSON.parse(this.selectedTemplate.placeholder_config)
        const example = {}
        Object.keys(config).forEach(key => {
          example[key] = `从文章内容中提取的 ${key} 值`
        })
        return `示例格式：\n${JSON.stringify(example, null, 2)}\n\n点击右侧 AI 助手自动生成`
      } catch (e) {
        return 'AI 将根据模板和文章内容自动生成 JSON 配置'
      }
    },

    // AI 上下文数据
    publishAIContextComputed() {
      return {
        post: this.currentPost,
        template: this.selectedTemplate,
        website: this.currentWebsite,
        current_form: {
          title: this.publishForm.title,
          slug: this.publishForm.slug,
          template_variables: this.publishForm.template_variables,
          seo_title: this.publishForm.seo_title,
          seo_keywords: this.publishForm.seo_keywords,
          seo_description: this.publishForm.seo_description
        }
      }
    }
  },
  created() {
    // 从路由参数中恢复website_id
    const websiteId = this.$route.query.website_id
    this.loadWebsites(websiteId)
    this.loadCategories()
    this.loadLanguages()
  },
  methods: {
    // 加载网站列表
    loadWebsites(websiteId) {
      GetWebsites().then(response => {
        if (response.data && response.data.data) {
          this.websites = response.data.data
        } else if (response.success) {
          this.websites = response.data
        }

        if (this.websites.length > 0) {
          // 如果有指定website_id，尝试找到对应的网站
          if (websiteId) {
            const website = this.websites.find(w => w.id === parseInt(websiteId))
            if (website) {
              this.currentWebsite = website
            } else {
              this.currentWebsite = this.websites[0]
            }
          } else {
            this.currentWebsite = this.websites[0]
          }

          this.loadTemplates()
          this.loadPosts()
        }
      })
    },

    // 网站切换
    handleWebsiteChange() {
      // 更新路由参数
      this.$router.replace({
        query: { ...this.$route.query, website_id: this.currentWebsite.id }
      })

      this.loadTemplates()
      this.loadPosts()
      // 清空选择
      this.selectedPosts = []
    },

    // 加载模板列表
    loadTemplates() {
      if (!this.currentWebsite) return

      const params = new URLSearchParams()
      params.append('website_id', this.currentWebsite.id)
      params.append('is_active', 'true')

      GetTemplates(null, params.toString()).then(response => {
        if (response.success) {
          this.templates = response.data
        }
      })
    },

    // 加载分类
    loadCategories() {
      GetCategories().then(response => {
        if (response.success) {
          this.categories = response.data || []
        }
      })
    },

    // 加载语言
    loadLanguages() {
      GetLanguages().then(response => {
        if (response.data && Array.isArray(response.data)) {
          this.languages = response.data
        }
      })
    },

    // 加载文章列表
    loadPosts() {
      if (!this.currentWebsite) {
        this.$message.warning('请先选择目标网站')
        return
      }

      this.postsLoading = true

      const params = {
        website_id: this.currentWebsite.id,
        page: this.postsQuery.page,
        pagesize: this.postsQuery.pagesize,
        kw: this.postsQuery.kw || '',
        category_id: this.postsQuery.category_id || '',
        language_id: this.postsQuery.language_id || '',
        publish_status: this.postsQuery.publish_status || 'all',
        writer_finished: this.postsQuery.writer_finished || ''
      }

      GetPostsForPublish(params).then(response => {
        if (response.success && response.data) {
          this.postsList = response.data.data || []
          this.postsTotal = response.data.total || 0
        }
        this.postsLoading = false
      }).catch(error => {
        console.error('加载文章列表失败:', error)
        this.postsLoading = false
      })
    },

    // 筛选条件改变
    handleFilter() {
      this.postsQuery.page = 1
      this.loadPosts()
    },

    // 清空选择
    clearSelection() {
      this.selectedPosts = []
    },

    // 状态文本转换
    getStatusText(status) {
      const statusMap = {
        'draft': '草稿',
        'ai_generating': 'AI生成中',
        'md_created': 'MD已创建',
        'source_code_generated': 'AI源码完成',
        'manual_optimized': '人工优化完毕',
        'ready_to_publish': '可发布',
        'review': '待审核',
        'published': '已发布',
        'archived': '已归档'
      }
      return statusMap[status] || status
    },

    // 检查文章是否已选择
    isPostSelected(postId) {
      return this.selectedPosts.some(p => p.id === postId)
    },

    // 切换文章选择
    togglePostSelection(post) {
      if (this.isPostSelected(post.id)) {
        this.removeFromSelection(post)
      } else {
        this.selectedPosts.push({ ...post })
      }
    },

    // 从选择中移除
    removeFromSelection(post) {
      const index = this.selectedPosts.findIndex(p => p.id === post.id)
      if (index > -1) {
        this.selectedPosts.splice(index, 1)
      }
    },

    // 打开发布抽屉
    openPublishDrawer(post) {
      if (!this.templates.length) {
        this.$message.warning('请先为该网站创建模板')
        return
      }

      this.currentPost = post

      // 基础表单数据
      const baseForm = {
        post_id: post.id,
        title: post.title,
        slug: this.generateSlug(post.title),
        template_id: this.templates.length > 0 ? this.templates[0].id : null,
        template_variables: '',
        feature_image: '', // 特色图片
        page_type: 'blog',
        status: 'published',
        seo_title: post.title,
        seo_keywords: post.tags || '',
        seo_description: post.excerpt || post.description || ''
      }

      // 如果post有关联的页面数据，回填模板变量和其他信息
      if (post.published_page) {
        baseForm.template_variables = post.published_page.content_data || ''
        baseForm.feature_image = post.published_page.feature_image || ''
        baseForm.template_id = post.published_page.template_id || baseForm.template_id

        // 回填 slug，确保有 blog/ 前缀
        let slug = post.published_page.slug || baseForm.slug
        if (slug && !slug.startsWith('blog/')) {
          slug = 'blog/' + slug.replace(/^\/+/, '')
        }
        baseForm.slug = slug

        baseForm.page_type = post.published_page.page_type || baseForm.page_type
        baseForm.status = post.published_page.status || baseForm.status
        baseForm.seo_title = post.published_page.meta_title || baseForm.seo_title
        baseForm.seo_keywords = post.published_page.meta_keywords || baseForm.seo_keywords
        baseForm.seo_description = post.published_page.meta_description || baseForm.seo_description
      }

      this.publishForm = baseForm
      this.publishDrawerTitle = post.is_published_to_current ? `更新页面配置 - ${post.title}` : `配置页面 - ${post.title}`
      this.publishDrawerVisible = true
    },

    // 生成 slug（直接生成文件名，不添加blog/前缀，避免相对路径问题）
    generateSlug(title) {
      const slug = title
        .toLowerCase()
        .replace(/[^\w\s-]/g, '')
        .replace(/\s+/g, '-')
        .substring(0, 50)
      // 博客文章直接部署到根目录，避免相对路径错误
      return slug
    },

    // 确认发布
    handlePublish() {
      this.$refs.publishForm.validate(valid => {
        if (!valid) return

        this.publishLoading = true

        const data = {
          website_id: this.currentWebsite.id,
          post_id: this.publishForm.post_id,
          template_id: this.publishForm.template_id,
          title: this.publishForm.title,
          slug: this.publishForm.slug,
          page_type: this.publishForm.page_type,
          status: this.publishForm.status,
          seo_title: this.publishForm.seo_title,
          seo_keywords: this.publishForm.seo_keywords,
          seo_description: this.publishForm.seo_description,
          template_variables: this.publishForm.template_variables,
          feature_image: this.publishForm.feature_image
        }

        PublishBlog(data).then(response => {
          if (response.success) {
            this.$message.success(response.msg || '页面配置已保存')
            this.publishDrawerVisible = false

            // 从已选择列表中移除
            this.removeFromSelection({ id: this.publishForm.post_id })

            // 刷新列表
            this.loadPosts()
          } else {
            this.$message.error(response.msg || '保存失败')
          }
        }).catch(error => {
          console.error('保存失败:', error)
          this.$message.error('保存失败，请稍后重试')
        }).finally(() => {
          this.publishLoading = false
        })
      })
    },

    // 批量配置
    batchPublish() {
      if (this.selectedPosts.length === 0) {
        this.$message.warning('请先选择要配置的文章')
        return
      }

      if (!this.templates.length) {
        this.$message.warning('请先为该网站创建模板')
        return
      }

      this.$confirm(`确定要批量发布 ${this.selectedPosts.length} 篇文章吗？将使用默认模板。`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          website_id: this.currentWebsite.id,
          template_id: this.templates[0].id,
          post_ids: this.selectedPosts.map(p => p.id)
        }

        const loading = this.$loading({
          lock: true,
          text: '批量发布中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        BatchPublishBlog(data).then(response => {
          loading.close()
          if (response.success) {
            const result = response.data
            this.$message.success(`批量发布完成: 成功 ${result.success} 篇，失败 ${result.failed} 篇`)
            this.selectedPosts = []
            this.loadPosts()
          } else {
            this.$message.error(response.msg || '批量发布失败')
          }
        }).catch(error => {
          loading.close()
          console.error('批量发布失败:', error)
          this.$message.error('批量发布失败，请稍后重试')
        })
      })
    },

    // 分页大小改变
    handlePostsSizeChange(val) {
      this.postsQuery.pagesize = val
      this.postsQuery.page = 1
      this.loadPosts()
    },

    // 分页页码改变
    handlePostsPageChange(val) {
      this.postsQuery.page = val
      this.loadPosts()
    },

    // 预览文章
    previewPost(post) {
      this.$alert(post.content || '暂无内容', post.title, {
        confirmButtonText: '关闭',
        dangerouslyUseHTMLString: true
      })
    },

    // 部署博客到静态网站
    handleDeployBlog(post) {
      // 检查是否已配置页面
      if (!post.is_published_to_current || !post.current_website_page_id) {
        this.$message.warning('请先配置页面参数')
        return
      }

      this.$confirm('确认要将此博客部署到静态网站吗？将生成HTML文件并保存到blog/目录', '部署确认', {
        confirmButtonText: '确定部署',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在部署...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        DeployBlogToStatic({
          page_id: post.current_website_page_id
        }).then(response => {
          loading.close()

          if (response.success) {
            this.$message.success(response.msg || '部署成功')
            // 可选：显示部署详情
            if (response.data && response.data.file_path) {
              this.$notify({
                title: '部署成功',
                message: `文件已保存到: ${response.data.file_path}`,
                type: 'success',
                duration: 5000
              })
            }
          } else {
            this.$message.error(response.msg || '部署失败')
          }
        }).catch(error => {
          loading.close()
          console.error('部署失败:', error)
          this.$message.error('部署失败，请稍后重试')
        })
      }).catch(() => {
        // 用户取消
      })
    },

    // 模板切换时清空变量配置
    handleTemplateChange() {
      this.publishForm.template_variables = ''
    },

    // AI生成特色图片
    // 打开特色图片生成对话框
    openFeatureImageDialog() {
      if (!this.currentPost || !this.currentPost.title) {
        this.$message.warning('请先选择文章')
        return
      }

      if (!this.currentWebsite) {
        this.$message.warning('请先选择目标网站')
        return
      }

      // 重置对话框状态
      this.aiImagePrompt = ''
      this.aiImageAspectRatio = '21:9'
      this.aiImageQuality = 85
      this.aiImageGenerationLog = ''
      this.generatedImagePreview = ''

      // 打开对话框
      this.featureImageDialogVisible = true

      // 自动生成图片描述
      this.regenerateImagePrompt()
    },

    // 重新生成图片Prompt
    async regenerateImagePrompt() {
      this.generatingPrompt = true
      this.aiImagePrompt = '正在生成图片描述...'

      try {
        // 使用新的API接口：根据post_id生成feature image prompt
        const promptResponse = await request({
          url: '/static_web/api/ai/generate_feature_image_prompt_by_post/',
          method: 'post',
          data: {
            post_id: this.currentPost.id,
            aspect_ratio: this.aiImageAspectRatio
          }
        })

        if (promptResponse.success && promptResponse.data && promptResponse.data.prompt) {
          this.aiImagePrompt = promptResponse.data.prompt
          this.$message.success('图片描述生成成功')
        } else {
          this.aiImagePrompt = 'A professional, high-quality feature image for blog post'
          this.$message.warning('使用默认描述')
        }
      } catch (error) {
        console.error('生成图片描述失败:', error)
        this.aiImagePrompt = 'A professional, high-quality feature image for blog post'
        this.$message.error('生成图片描述失败，使用默认描述')
      } finally {
        this.generatingPrompt = false
      }
    },

    // AI生成特色图片
    async handleAIGenerateFeatureImage() {
      if (!this.aiImagePrompt.trim()) {
        this.$message.warning('请输入图片描述')
        return
      }

      this.aiGeneratingImage = true
      this.aiImageGenerationLog = ''
      this.generatedImagePreview = ''

      try {
        // 获取token和projectId
        const token = this.$store.getters.token
        const projectId = this.$store.getters.projectId

        const requestBody = {
          post_id: 0,
          page_title: this.currentPost.title || '博客特色图片',
          website_id: this.currentWebsite.id,
          custom_prompt: this.aiImagePrompt,
          style: 'professional',
          aspect_ratio: this.aiImageAspectRatio,
          compress_quality: this.aiImageQuality
        }

        console.log('[AI生成] 请求参数:', requestBody)

        // 使用fetch API处理streaming响应
        const response = await fetch(process.env.VUE_APP_BASE_API + '/cms/api/ai_task_feature_image_generate/', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': token,
            'PTOKEN': projectId
          },
          body: JSON.stringify(requestBody)
        })

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const reader = response.body.getReader()
        const decoder = new TextDecoder()
        let result = null

        // 读取流式响应
        // eslint-disable-next-line no-constant-condition
        while (true) {
          const { value, done } = await reader.read()
          if (done) break

          const chunk = decoder.decode(value, { stream: true })
          const lines = chunk.split('\n')

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const content = line.substring(6)

              // 检查是否包含最终结果
              const match = content.match(/<!--FINAL_RESULT:\s*(.+?)\s*-->/)
              if (match) {
                try {
                  result = JSON.parse(match[1])
                } catch (e) {
                  console.error('解析最终结果失败:', e)
                }
              } else {
                // 实时显示日志
                this.aiImageGenerationLog += content + '\n'
              }
            }
          }
        }

        // 处理最终结果
        if (result && result.success && result.images && result.images.length > 0) {
          const generatedImage = result.images[0]
          this.generatedImagePreview = generatedImage.url

          console.log('[AI生成] 图片生成成功:', {
            url: generatedImage.url,
            filename: generatedImage.filename,
            aspect_ratio: generatedImage.aspect_ratio
          })

          this.$message.success('特色图片生成成功！')
        } else {
          throw new Error(result?.msg || '图片生成失败')
        }
      } catch (error) {
        console.error('生成特色图片失败:', error)
        this.$message.error('生成特色图片失败: ' + error.message)
        this.aiImageGenerationLog += '\n\n错误: ' + error.message
      } finally {
        this.aiGeneratingImage = false
      }
    },

    // 确认使用生成的图片
    confirmUseGeneratedImage() {
      if (this.generatedImagePreview) {
        this.publishForm.feature_image = this.generatedImagePreview
        this.featureImageDialogVisible = false
        this.$message.success('特色图片已设置')
      }
    },

    // 对话框关闭事件
    handleFeatureImageDialogClose() {
      // 重置状态
      this.aiImagePrompt = ''
      this.aiImageGenerationLog = ''
      this.generatedImagePreview = ''
      this.aiGeneratingImage = false
      this.generatingPrompt = false
    },

    // AI 填充表单数据
    handleAIFillForm(data) {
      try {
        console.log('AI 返回的数据:', data)

        // 遍历 AI 返回的数据，填充到表单中
        Object.keys(data).forEach(key => {
          // 跳过不存在的字段
          if (!(key in this.publishForm)) {
            return
          }

          const value = data[key]

          // 跳过对象类型的值（如 website、template 对象）
          if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
            console.log(`跳过对象字段: ${key}`, value)
            return
          }

          // 对于 JSON 字符串字段，确保格式化
          if (key === 'template_variables' && typeof value === 'string') {
            try {
              const parsed = JSON.parse(value)
              this.publishForm[key] = JSON.stringify(parsed, null, 2)
            } catch (e) {
              this.publishForm[key] = value
            }
          } else if (key === 'template_variables' && typeof value === 'object') {
            // 如果是对象，转换为格式化的 JSON 字符串
            this.publishForm[key] = JSON.stringify(value, null, 2)
          } else {
            // 直接赋值
            this.publishForm[key] = value
          }
        })

        this.$message.success('AI 数据已填充到表单')

        // 清除表单验证错误
        if (this.$refs.publishForm) {
          this.$refs.publishForm.clearValidate()
        }
      } catch (error) {
        console.error('填充表单失败:', error)
        this.$message.error('填充表单失败: ' + error.message)
      }
    }
  }
}
</script>

<style scoped>
.filter-container {
  padding: 10px 0;
  margin-bottom: 10px;
}

.filter-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

/* 已选择的文章卡片 */
.selected-posts-card {
  margin-bottom: 20px;
}

.selected-posts-list {
  padding: 10px 0;
}

.selected-post-item {
  display: flex;
  align-items: center;
  padding: 15px;
  margin-bottom: 10px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  transition: all 0.3s;
}

.selected-post-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-color: #67C23A;
}

/* 抽屉内容 */
.drawer-content {
  padding: 0 20px 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.filter-bar {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #EBEEF5;
}

/* 文章列表 */
.posts-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}

.post-item {
  display: flex;
  align-items: center;
  padding: 20px;
  margin-bottom: 15px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  transition: all 0.3s;
}

.post-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-color: #409EFF;
}

.post-item.is-selected {
  background-color: #f0f9ff;
  border-color: #67C23A;
}

.post-item.published-to-current {
  background-color: #f0f9ff;
}

.post-checkbox {
  margin-right: 15px;
}

.post-content {
  flex: 1;
  min-width: 0;
  margin-right: 20px;
}

.post-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.post-meta {
  margin-bottom: 8px;
  font-size: 12px;
  color: #909399;
}

.meta-item {
  margin-left: 15px;
}

.post-excerpt {
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 发布状态和操作区域 */
.post-status-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10px;
  min-width: 250px;
}

.status-tags {
  display: flex;
  align-items: center;
  gap: 5px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.post-actions {
  margin-left: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.drawer-footer {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #EBEEF5;
  text-align: right;
}

.mt-pagination {
  margin-top: 20px;
  text-align: right;
}

/* 抽屉左右布局 */
.drawer-split-layout {
  display: flex;
  height: calc(100vh - 60px);
  gap: 20px;
}

.left-panel {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  border-right: 1px solid #EBEEF5;
}

.right-panel-ai {
  width: 500px;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #f5f7fa;
}

.ai-panel-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #1EB7E6;
}
</style>
